import superagent from 'superagent'
import utils from '../utils/'
import { Toast } from 'antd-mobile'
import NProgress from 'nprogress'

const methods = [
  'get',
  'head',
  'post',
  'put',
  'del',
  'options',
  'patch'
];

const ERRORS ={
  '11001': '请求参数错误',
  '1500': '微信验证失败',
  '400': '请求参数错误',
  '401': '未注册',
  '403': '未授权',
  '404': '页面未找到',
  '405': '请求方法未允许',
  '406': '请求内容类型错误',
  '408': '请求超时',
  '500': '内部服务器错误',
  '501': '未实现',
  '502': '网关错误',
  '503': '服务无法获得',
  '504': '网关超时',
  '505': '不支持的HTTP版本'
}

const debug = process.env.NODE_ENV !== 'production';

class _Api {

  constructor(opts) {

    this.opts = opts || {};

    if (!this.opts.baseURI)
      throw new Error('baseURI option is required');

    methods.forEach(method =>
      this[method] = (path, otherOptions)=>(data={}) => new Promise((resolve, reject) => {
        const request = superagent[method](this.opts.baseURI + path);
        let loading = otherOptions && otherOptions.loading;
        this.opts.headers && request.set( this.opts.headers );
        this.opts.timeout && request.timeout( this.opts.timeout );
        // 是否允许跨域带cookie
        this.opts.withCredentials && request.withCredentials();

        loading ? Toast.loading('加载中...') : NProgress.start();

        method === 'get' ? request.query(data) : request.send(data);
        request.end((err, { body } = {}) => {
          loading ? Toast.hide() : NProgress.done(true);
          if(err){
            var errInfo = ERRORS[err.status];
            Toast.info(errInfo || err.message || '未知错误');
            reject( body  || err, request );
          }else{
            if(body.errorCode && body.errorCode!==200 && body.errorCode!==401){
              Toast.info(body.moreInfo || '未知错误', 3);
            }
            resolve(body, request);
          }
        });
      })
    );

  }

}

const Api = _Api;

export default Api;
